package com.ddf.norman.config;

import com.alibaba.fastjson.JSONObject;
import com.ddf.publics.entity.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName: UserLoginAuthenticationSuccessHandler.java
 * @Description: 登录成功后的处理
 * @author: norman
 * @date:  2020-06-11 19:36
 * @version V1.0
 */
@Component("UserLoginAuthenticationSuccessHandler")
public class UserLoginAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(200);

        PrintWriter out = response.getWriter();
        JSONObject object = new JSONObject();

        RequestCache requestCache = new HttpSessionRequestCache();
        String url = null;
        SavedRequest savedRequest = requestCache.getRequest(request,response);
        if(savedRequest != null){
            url = savedRequest.getRedirectUrl();
        }
        if(url == null || url.indexOf("/error") != -1 || url.indexOf("/logout") != -1 || url.indexOf("?logout") != -1){
            url = "/index";
        }

        object.put("msg","success");
        object.put("url",url);
        out.print(object.toJSONString());
        out.flush();
        out.close();
    }
}